import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.3
import Qt.labs.platform 1.0
import SerialPort 1.0
import FileObject 1.0

Window {
    id: window
    visible: true
    width: 640
    height: 480
    title: "Uupdater"

    property var defaultParam: {
        "databit": SerialPort.Data8,
        "stopbit": SerialPort.OneStop,
        "baud": SerialPort.Baud115200,
        "parity": SerialPort.NoParity
    }

    function setParam(par) {

        // imei, portName, databit, stopbit, baud, parity
        for (var m = 0; m < portCb.model.count; m++) {
            if (portCb.model.get(m).text === par.portName) {
                portCb.currentIndex = m
                break
            }
        }
        for (var m = 0; m < baudCb.model.count; m++) {
            if (baudCb.model.get(m).choice === par.baud) {
                baudCb.currentIndex = m
                break
            }
        }
        for (var m = 0; m < parityCb.model.count; m++) {
            if (parityCb.model.get(m).choice === par.parity) {
                parityCb.currentIndex = m
                break
            }
        }
        for (var m = 0; m < stopbitCb.model.count; m++) {
            if (stopbitCb.model.get(m).choice === par.stopbit) {
                stopbitCb.currentIndex = m
                break
            }
        }
        for (var m = 0; m < databitCb.model.count; m++) {
            if (databitCb.model.get(m).choice === par.databit) {
                databitCb.currentIndex = m
                break
            }
        }
    }

    function getParam(par) {//        parSave.type = "Serial"
        //        parSave.imei = imeiText.text
        //        parSave.portName = portCb.currentText
        //        parSave.baudRate = baudCb.model.get(baudCb.currentIndex).choice
        //        parSave.parity = parityCb.model.get(parityCb.currentIndex).choice
        //        parSave.stopBits = stopbitCb.model.get(stopbitCb.currentIndex).choice
        //        parSave.dataBits = databitCb.model.get(databitCb.currentIndex).choice
        //        return parSave
    }

    Component.onCompleted: initUi()
    function initUi() {
        addPortInfo()
        setParam(defaultParam)
    }

    function addPortInfo() {
        var portList = sport.getPortsInfo()
        portCb.model.clear()
        for (var p in portList) {
            portCb.model.append({
                                    "text": portList[p]
                                })
        }
        portCb.currentIndex = 0
    }

    function switchPort() {
        if (sport.getStatus()) {
            sport.close()
            conBtn.text = "CONNECT"
            appendLog("串口 " + sport.portName + " 已经断开")
        } else {
            if (sport.open()) {
                conBtn.text = "DISCONNECT"
                clearLog()
                appendLog("串口 " + sport.portName + " 连接成功")
            } else {
                conBtn.text = "CONNECT"
                appendLog("串口 " + sport.portName + " 连接失败:" + sport.error())
            }
        }
    }
    function readFw() {
        fwContent = file.readByte()
        let size = file.size()
        appendLog("打开固件，文件长度: " + size)
    }

    function clearLog() {
//        logPage.clear()
    }

    function appendLog(log) {
        logPage.addLog(log)
    }

    function setProgress(v) {
        progressBar.value = v
    }

    FileObject {
        id: file
    }

    SerialPort {
        id: sport
        onAddDownLog: appendLog(msg)
        onDownloadProgress: appendLog("下载数据包应答:" + index + ", 进度：" + progress)
        onDownloadRunning: {
            startBtn.text = "下载中"
            appendLog("收到更新固件应答...")
        }
        onDownloadComplete: {
            startBtn.text = "下载"
            appendLog("下载完成\r\n")
        }
        onSpeedUpdate: speedText.text = bytes
        onPackReplyTimeout: appendLog("开始续传")
        onProgressChanged: setProgress(val * 100)
        portName: portCb.currentText
        baudRate: baudCb.model.get(baudCb.currentIndex).choice
        parity: parityCb.model.get(parityCb.currentIndex).choice
        stopBits: stopbitCb.model.get(stopbitCb.currentIndex).choice
        dataBits: databitCb.model.get(databitCb.currentIndex).choice
    }

    Rectangle {
        id: rectangle
        anchors.leftMargin: 325
        anchors.topMargin: 14
        anchors.rightMargin: 14
        anchors.bottomMargin: 245
        anchors.fill: parent

        ComboBox {
            id: portCb
            width: 170
            height: 30
            anchors.verticalCenter: label4.verticalCenter
            anchors.left: label4.right
            anchors.leftMargin: 20
            font.pointSize: 9
            model: ListModel {}
            onPressedChanged: addPortInfo()
        }

        ComboBox {
            id: databitCb
            y: 86
            width: 170
            height: 30
            anchors.verticalCenter: label.verticalCenter
            visible: true
            font.pointSize: 9
            anchors.left: baudCb.left
            anchors.leftMargin: 0
            anchors.topMargin: 0
            //        anchors.top: label3.top
            currentIndex: 3
            textRole: "text"
            model: ListModel {
                ListElement {
                    text: "5 bit"
                    choice: SerialPort.Data5
                }
                ListElement {
                    text: "6 bit"
                    choice: SerialPort.Data6
                }
                ListElement {
                    text: "7 bits"
                    choice: SerialPort.Data7
                }
                ListElement {
                    text: "8 bits"
                    choice: SerialPort.Data8
                }
            }
        }

        ComboBox {
            id: stopbitCb
            y: 132
            width: 170
            height: 30
            anchors.left: label2.right
            anchors.leftMargin: 20
            anchors.verticalCenter: label2.verticalCenter
            visible: true
            font.pointSize: 9
            anchors.topMargin: 0
            //        anchors.top: label4.top
            textRole: "text"
            model: ListModel {
                ListElement {
                    text: "One bit"
                    choice: SerialPort.OneStop
                }
                ListElement {
                    text: "One hal fbit"
                    choice: SerialPort.OneAndHalfStop
                }
                ListElement {
                    text: "Two bits"
                    choice: SerialPort.TwoStop
                }
            }
        }

        ComboBox {
            id: baudCb
            y: 51
            width: 170
            height: 30
            anchors.verticalCenter: label1.verticalCenter
            visible: true
            font.pointSize: 7
            anchors.left: label1.right
            anchors.leftMargin: 20
            anchors.topMargin: 0
            //        anchors.top: label1.top
            currentIndex: 2
            textRole: "text"
            model: ListModel {
                ListElement {
                    text: "2400"
                    choice: SerialPort.Baud2400
                }
                ListElement {
                    text: "4800"
                    choice: SerialPort.Baud4800
                }
                ListElement {
                    text: "9600"
                    choice: SerialPort.Baud9600
                }
                ListElement {
                    text: "19200"
                    choice: SerialPort.Baud19200
                }
                ListElement {
                    text: "38400"
                    choice: SerialPort.Baud38400
                }
                ListElement {
                    text: "57600"
                    choice: SerialPort.Baud57600
                }
                ListElement {
                    text: "115200"
                    choice: SerialPort.Baud115200
                }
            }
        }

        ComboBox {
            id: parityCb
            y: 170
            width: 170
            height: 30
            anchors.verticalCenter: label3.verticalCenter
            visible: true
            font.pointSize: 9
            anchors.left: baudCb.left
            anchors.leftMargin: 0
            anchors.topMargin: 0
            //        anchors.top: label2.top
            currentIndex: 0
            textRole: "text"
            model: ListModel {
                ListElement {
                    text: "No parity"
                    choice: SerialPort.NoParity
                }
                ListElement {
                    text: "Even parity"
                    choice: SerialPort.EvenParity
                }
                ListElement {
                    text: "Odd parity"
                    choice: SerialPort.OddParity
                }
                ListElement {
                    text: "Space parity"
                    choice: SerialPort.SpaceParity
                }
                ListElement {
                    text: "Mark parity"
                    choice: SerialPort.MarkParity
                }
            }
        }

        Label {
            id: label
            height: 20
            text: qsTr("数据位:")
            anchors.left: label1.left
            anchors.leftMargin: 0
            anchors.top: label1.bottom
            anchors.topMargin: 20
            font.pointSize: 12
        }

        Label {
            id: label1
            height: 20
            text: qsTr("波特率:")
            anchors.top: label4.bottom
            anchors.topMargin: 20
            anchors.left: label4.left
            anchors.leftMargin: 0
            font.pointSize: 12
        }

        Label {
            id: label2
            height: 20
            text: qsTr("停止位:")
            anchors.left: label.left
            anchors.leftMargin: 0
            anchors.top: label.bottom
            anchors.topMargin: 20
            font.pointSize: 12
        }

        Label {
            id: label3
            height: 20
            text: qsTr("校验位:")
            anchors.left: label2.left
            anchors.leftMargin: 0
            anchors.top: label2.bottom
            anchors.topMargin: 20
            font.pointSize: 12
        }

        Label {
            id: label4
            height: 20
            text: qsTr("串口名:")
            anchors.left: parent.left
            anchors.leftMargin: 10
            anchors.top: parent.top
            anchors.topMargin: 20
            font.pointSize: 12
        }
    }

    Button {
        id: fileBtn
        x: 454
        y: 338
        text: qsTr("选择固件")
        height: 40
        width: 140

        onClicked: {

            appendLog("选择固件路径:" + file.read())
        }
    }

    //    FileDialog {
    //        id: fileDialog
    //        onAccepted: {
    //            fwPath = fileDialog.file.toString().substring(8)
    //            appendLog("选择固件路径:" + fwPath)
    //            setProgress(0)
    //            readFw()
    //        }
    //        nameFilters: ["Bin files (*.bin *.hex *.rbl)", "All files (*)"]
    //    }
    Button {
        id: startBtn
        x: 138
        y: 417
        width: 140
        height: 40
        highlighted: true
        //        enabled: imeiText.text.length > 0
        text: qsTr("下载")
        anchors.horizontalCenterOffset: 204
        font.pointSize: 10
        anchors.bottom: parent.bottom
        anchors.bottomMargin: 23
        anchors.horizontalCenter: parent.horizontalCenter
        onClicked: {
            sport.startUpdate(file.content())
        }
    }

    Button {
        id: conBtn
        x: 133
        y: 236
        width: 141
        height: 40
        text: qsTr("连接")
        anchors.bottomMargin: 197
        anchors.horizontalCenter: parent.horizontalCenter
        font.pointSize: 10
        anchors.bottom: parent.bottom
        anchors.horizontalCenterOffset: 204
        onClicked: switchPort()
    }

    ProgressBar {
        id: progressBar
        x: 15
        y: 417
        width: 292
        height: 40
        indeterminate: false
        font.pointSize: 15
        enabled: true
        to: 100
        value: 99
    }

    Rectangle {
              id: frame
              width: 304
              height: 373
              border.color: "#b1b1b1"
              anchors.left: parent.left
              anchors.leftMargin: 15
              anchors.top: parent.top
              anchors.topMargin: 14
              clip: true
              focus: true

             LogPage {
                 id :logPage
                 anchors.rightMargin: 1
                 anchors.leftMargin: 1
                 anchors.bottomMargin: 10
                 anchors.topMargin: 1
                 anchors.fill: parent
             }
    }

    Text {
        id: speedText
        y: 429
        width: 50
        height: 25
        text: qsTr("1152000")
        anchors.left: progressBar.right
        anchors.leftMargin: 5
        anchors.verticalCenter: progressBar.verticalCenter
        verticalAlignment: Text.AlignVCenter
        horizontalAlignment: Text.AlignHCenter
        font.pixelSize: 13


    }
    Label {
        id: label5
        y: 2
        width: 50
        height: 25
        text: qsTr("Byte/s")
        verticalAlignment: Text.AlignVCenter
        horizontalAlignment: Text.AlignHCenter
        anchors.left: speedText.right
        anchors.leftMargin: 5
        anchors.verticalCenter: speedText.verticalCenter
    }
}

/*##^##
Designer {
    D{i:36;anchors_x:45}D{i:43;anchors_height:373;anchors_width:310;anchors_y:0}D{i:42;anchors_x:15;anchors_y:14}
D{i:44;anchors_x:318}D{i:45;anchors_x:56}
}
##^##*/

